package com.wuwei.elearning.utils;

import com.alibaba.fastjson.JSONObject;
import com.wuwei.elearning.utils.result.Result;
import com.wuwei.elearning.utils.token.Token;
import com.wuwei.elearning.utils.token.TokenManager;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
 * 进行微信云开发请求云数据库的类
 */
@Component
public class WxUtils {

    @Autowired
    private Token token;


    @Value("${myWx.env}")
    private String env;

    public Result getSqlFromWxPost (String query) throws Exception {
        String token = this.testToken();
        String host = "https://api.weixin.qq.com";
        String path = "/tcb/databasequery";
        String method = "POST";
        //请求头
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json; charset=UTF-8");
        //请求参数
        Map<String, String> querys = new HashMap<>();
        querys.put("access_token",token);
        //请求体
        Map<String, String> bodys = new HashMap<>();
        bodys.put("env",env);
        bodys.put("query",query);
        String jsonString = JSONObject.toJSONString(bodys);
        HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, jsonString);
        assert response != null;
        System.out.println(response.toString());
//            获取response的body
        String fanhui = EntityUtils.toString(response.getEntity());
        JSONObject returnObj = JSONObject.parseObject(fanhui);
        return Result.ok(returnObj);
    }

    public JSONObject myDoGet (String query) throws Exception {
        String token = this.testToken();
        String host = "https://api.weixin.qq.com";
        String path = "/tcb/databasequery";
        String method = "POST";
        //请求头
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json; charset=UTF-8");
        //请求参数
        Map<String, String> querys = new HashMap<>();
        querys.put("access_token",token);
        //请求体
        Map<String, String> bodys = new HashMap<>();
        bodys.put("env",env);
        bodys.put("query",query);
        String jsonString = JSONObject.toJSONString(bodys);
        HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, jsonString);
        assert response != null;
        System.out.println(response.toString());
//            获取response的body
        String fanhui = EntityUtils.toString(response.getEntity());
        JSONObject returnObj = JSONObject.parseObject(fanhui);
        return returnObj;
    }


    /**
     * 微信小程序对数据库进行操作的通用方法
     * @param bodys 请求参数如{
     *   "env":"test2-4a89da",
     *   "collection_name": "test_delete_collection"
     * }
     * @param host 域名，如https://api.weixin.qq.com
     * @param path 路径，如/tcb/databasecollectiondelete
     * @return
     * @throws Exception
     */
    public Result getSqlFromWxPost (Map bodys,String host,String path) throws Exception {
        String token = this.testToken();
        String method = "POST";
        //请求头
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json; charset=UTF-8");
        //请求参数
        Map<String, String> querys = new HashMap<>();
        querys.put("access_token",token);
        String jsonString = JSONObject.toJSONString(bodys);
        HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, jsonString);
        assert response != null;
        System.out.println(response.toString());
//            获取response的body
        String fanhui = EntityUtils.toString(response.getEntity());
        JSONObject returnObj = JSONObject.parseObject(fanhui);
        return Result.ok(returnObj);
    }

    /**
     * 每次发送请求前都要检查一下token
     * @return
     * @throws Exception
     */
    public String testToken() throws Exception {
        System.out.println(env);
        Date accessTokenCreateTime = token.getAccessTokenCreateTime();
        if (accessTokenCreateTime==null){//说明没创建过
            token = TokenManager.getAccess_Token();
        }
        boolean b = TokenManager.testToken(token.getAccessTokenCreateTime());
        if (!b){//说明过期了
            token = TokenManager.getAccess_Token();
        }
        return this.token.getToken();
    }
}
